package com.teen9g.infoplatformserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.hash.BloomFilter;
import com.teen9g.constant.RedisKey;
import com.teen9g.constant.UserConstant;
import com.teen9g.context.BaseContext;
import com.teen9g.dto.UserLoginDTO;
import com.teen9g.entity.User;
import com.teen9g.exception.PasswordErrorException;
import com.teen9g.exception.UserNotFoundException;
import com.teen9g.infoplatformserver.mapper.UserMapper;
import com.teen9g.infoplatformserver.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService {

    private final static String defaultAvatarUrl =
            "https://web-tn9g.oss-cn-hangzhou.aliyuncs.com/642ececc-629b-4a4e-aa6f-1f948894ad8e.jpg";


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, User> redisTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplateString;

    @Autowired
    private BloomFilter<Integer> userBloomFilter;

    /**
     * 获取全部用户信息
     *
     * @return
     */
    @Override
    public List<User> getUser() {
        return userMapper.getUser();
    }

    /**
     * 用户登录
     *
     * @param userLoginDTO 用户名和密码
     * @return 登录结果
     */
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();
        // 创建QueryWrapper对象，用于构建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("username", username);
        // 执行查询
        User user = userMapper.selectOne(queryWrapper);

        // 账号不存在
        if (user == null) {
            throw new UserNotFoundException("用户不存在哦");
        }

        // 密码错误
        if (!user.getPassword().equals(password)) {
            throw new PasswordErrorException("密码错误");
        }

        // 上面的异常都不是 返回查询到的实体
        // 先更新最近登录时间
        user.setRecentLoginTime(LocalDateTime.now());
        userMapper.updateById(user);
        BaseContext.setCurrentUserId(user.getId());
        BaseContext.setCurrentUser(user.getUsername());
        user.setPassword("你还想看密码？");
        return user;
    }

    /**
     * 用户注册
     *
     * @param userloginDTO 用户名和密码
     * @return 注册结果
     */
    @Override
    public String register(UserLoginDTO userloginDTO) {
        if (userloginDTO.getPassword().isEmpty() || userloginDTO.getUsername().isEmpty()) {
            return UserConstant.USER_REGISTER_EMPTY;
        }
        // 先查询是否存在该用户
        String username = userloginDTO.getUsername();

        // 创建QueryWrapper对象，用于构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<User>();

        // 构建查询条件
        queryWrapper.eq(User::getUsername, username);

        int count = userMapper.selectCount(queryWrapper);
        if (count != 0) {
            return UserConstant.USER_REGISTER_FOUND;
        } else {
            User build = User.builder()
                    .username(username)
                    .password(userloginDTO.getPassword())
                    .avatarUrl(defaultAvatarUrl)
                    .recentLoginTime(LocalDateTime.now())
                    .build();
            // 插入用户
            userMapper.insert(build);

            return UserConstant.USER_REGISTER_SUCCESS;
        }
    }

    @Override
    public User getById(Integer id) {
        // 先使用布隆过滤器判断 id 是否可能有效
        if (!userBloomFilter.mightContain(id)) {
            return null;
        }
        //先走Redis
        String key = RedisKey.USER_KEY_PREFIX + id;
        User user = redisTemplate.opsForValue().get(key);
        if (user != null) {
            user.setPassword(UserConstant.PASSWORD_CONFUSED);
            return user;
        }

        //Redis没有，再走数据库
        user = userMapper.selectById(id);
        if (user != null) {
            redisTemplate.opsForValue().set(key, user, RedisKey.USER_CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
            user.setPassword(UserConstant.PASSWORD_CONFUSED);
        }
        return user;
    }

    @Override
    public String getAvatar(Integer id) {
        // 先使用布隆过滤器判断 id 是否可能有效
        if (!userBloomFilter.mightContain(id)) {
            return null;
        }
        String key = RedisKey.USER_KEY_AVATAR_PREFIX + id;
        String avatar = redisTemplateString.opsForValue().get(key);
        if (avatar != null && !avatar.isEmpty()) {
            return avatar;
        }
        //Redis没有，再走数据库
        avatar = userMapper.getAvatarUrlByUserId(id);
        if (avatar != null && !avatar.isEmpty()) {
            redisTemplateString.opsForValue().set(key, avatar, RedisKey.USER_CACHE_EXPIRE_TIME, TimeUnit.MINUTES);
        }
        return avatar;
    }

    @Override
    public String updateAvatar(Integer id, String avatar) {
        try {
            userMapper.updateAvatarUrlByUserId(id, avatar);
            return UserConstant.USER_AVATAR_UPDATE_SUCCESS;
        } catch (Exception e) {
            return UserConstant.USER_AVATAR_UPDATE_FAIL;
        }
    }
}
